package com.tju.shortlink.project.service.impl;

import cn.hutool.core.util.StrUtil;
import com.tju.shortlink.project.service.IUrlTitleService;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

@Service
public class UrlTitleService implements IUrlTitleService {

    @SneakyThrows
    @Override
    public String getTitleByUrl(String url) {
        String title = null;
        URL targetUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        int responseCode = connection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            Document document = Jsoup.connect(url).get();
            title = document.title();
            if(StrUtil.isBlank(title)){
                String baseUrl = targetUrl.getProtocol() + "://" + targetUrl.getHost();
                if(!Objects.equals(baseUrl, url)){
                    return getTitleByUrl(baseUrl);
                }
            }
        }else{
            return "Error while fetching title";
        }
        return title;
    }
}
